from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from sqlalchemy.exc import SQLAlchemyError
from app.exception import BaseError, ResourceNotFoundError, ValidationError, DatabaseError, AuthorizationError

def register_exception_handlers(app: FastAPI):
    """注册全局异常处理器"""
    
    # 处理自定义基础异常
    @app.exception_handler(BaseError)
    async def base_error_handler(request: Request, exc: BaseError):
        return JSONResponse(
            status_code=200,  # 统一使用 200 状态码，通过 code 字段表示业务错误码
            content={
                "code": exc.code,
                "errorMsg": exc.message,
                "data": None
            }
        )
    
    # 处理验证异常
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        # 格式化验证错误信息
        error_msg = "数据验证错误: "
        for error in exc.errors():
            error_msg += f"{error.get('loc', [''])[(-1)]}: {error.get('msg', '')}, "
        
        return JSONResponse(
            status_code=200,
            content={
                "code": 400,
                "errorMsg": error_msg.rstrip(", "),
                "data": None
            }
        )
    
    # 处理SQLAlchemy异常
    @app.exception_handler(SQLAlchemyError)
    async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError):
        return JSONResponse(
            status_code=200,
            content={
                "code": 500,
                "errorMsg": f"数据库错误: {str(exc)}",
                "data": None
            }
        )
    
    # 处理404错误
    @app.exception_handler(404)
    async def not_found_exception_handler(request: Request, exc):
        return JSONResponse(
            status_code=200,
            content={
                "code": 404,
                "errorMsg": "请求的资源不存在",
                "data": None
            }
        )
    
    # 处理500错误
    @app.exception_handler(500)
    async def internal_exception_handler(request: Request, exc):
        return JSONResponse(
            status_code=200,
            content={
                "code": 500,
                "errorMsg": "服务器内部错误",
                "data": None
            }
        )
